import { useEffect } from "react";
import { message, Table, Pagination, Tag } from "antd";
import { Button, Card as SemiCard } from "@douyinfe/semi-ui";
import { useModel, history } from "umi";
import { useReactive } from "ahooks";
import { AllReviewedMembers, UpdateMemberStatus, UpdateMemberOmIfim, RemoveMember } from "../_graphql";

export default function AllMembersPage() {
    const { remoteData, basePlatformUrl, windowInnerHeight, graphqlFetch } = useModel("global");
    const { baseInfo } = useModel("person.info");
    const { organizationUuid } = useModel("organization.info");

    const state = useReactive({
        loading: false,
        members: [],
        totalCount: 0,
        pageSize: 20,
        page: 1,
    });

    const loadMembers = async (first, offset) => {
        state.loading = true;
        let res = await graphqlFetch({
            query: AllReviewedMembers,
            variables: {
                first: first || state.pageSize,
                offset: offset || 0,
            },
        });
        state.members = res?.a?.nodes || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.loading = false;
        if (state.totalCount === 0) history.replace("/all");
    };

    useEffect(() => {
        organizationUuid && loadMembers();
    }, [organizationUuid]);

    const updateMemberStatus = async (omUuid, omAust) => {
        let res = await remoteData({
            object: "base-platform-management-service",
            serviceUrl: basePlatformUrl,
            serviceName: "/api/v1/person/organization/relation",
            params: { personUuid: omUuid, organizationUuid },
        });
        if (res) {
            res = await graphqlFetch({
                query: UpdateMemberStatus,
                variables: {
                    omUuid,
                    omAust,
                },
            });
            if (res) {
                await loadMembers();
                message.success("成功更改组织成员状态");
            }
        }
    };

    const updateMemberOmIfim = async (omUuid, omIfim) => {
        let res = await graphqlFetch({
            query: UpdateMemberOmIfim,
            variables: {
                omUuid,
                omIfim,
            },
        });
        if (res) {
            await loadMembers();
            message.success("成功更改成员为内部成员");
        }
    };

    const removeMember = async (omUuid) => {
        let res = await remoteData({
            object: "base-platform-management-service",
            serviceUrl: basePlatformUrl,
            serviceName: "/api/v1/person/organization/remove",
            params: { personUuid: omUuid, organizationUuid },
        });
        if (res) {
            res = await graphqlFetch({
                query: RemoveMember,
                variables: {
                    omUuid,
                },
            });
            if (res) {
                await loadMembers();
                message.success("成功移除组织成员");
            }
        }
    };

    const columns = [
        { title: "序号", dataIndex: "omName", align: "center", width: 60, render: (_, record, i) => i + 1 },
        { title: "成员姓名", dataIndex: "omName", align: "center" },
        { title: "性别", dataIndex: "omRoge", align: "center", width: 80 },
        {
            title: "内部成员？",
            dataIndex: "omIfim",
            align: "center",
            render: (_, record) =>
                record.omIfim ? (
                    "内部"
                ) : (
                    <span>外部{record.omAust === "已认证" && <a onClick={() => updateMemberOmIfim(record.omUuid, true)}>(转内部)</a>}</span>
                ),
        },
        { title: "职位", dataIndex: "omPosi", align: "center" },
        { title: "加入理由", dataIndex: "omCaus", align: "center", width: 360 },
        {
            title: "成员状态",
            dataIndex: "omAust",
            align: "center",
            render: (_, record) => {
                let color;
                if (_ === "待认证" || _ === "重新认证") color = "processing";
                if (_ === "已认证") color = "success";
                if (_ === "已退出" || _ === "已移除") color = "error";
                if (record.omAust === "待认证") {
                    return (
                        <span>
                            <Tag color={color}>{_}</Tag>(<a onClick={() => updateMemberStatus(record.omUuid, "已认证")}>通过</a> |{" "}
                            <a onClick={() => removeMember(record.omUuid)}>拒绝</a>)
                        </span>
                    );
                } else if (record.omAust === "已认证") {
                    if (record.omUuid === baseInfo.uuid) return record.omAust;
                    return (
                        <span>
                            <Tag color={color}>{_}</Tag>(<a onClick={() => removeMember(record.omUuid)}>移除</a>)
                        </span>
                    );
                } else {
                    return record.omAust;
                }
            },
        },
    ];

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 53 - 60;

    return (
        <SemiCard
            title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>待认证成员列表</span>}
            headerExtraContent={<Button onClick={() => loadMembers()}>刷新</Button>}
            headerStyle={{ padding: "10px 14px" }}
            shadows="always"
            bordered={false}
            bodyStyle={{ padding: 0, height: cardBodyHeight }}
            footerStyle={{ padding: 0 }}
            footerLine={true}
            footer={
                <div style={{ padding: 14, display: "flex", justifyContent: "space-between" }}>
                    <div></div>
                    <Pagination
                        total={state.totalCount}
                        showTotal={(total, range) => `当前显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                        pageSize={state.pageSize}
                        current={state.page}
                        showSizeChanger={false}
                        onChange={(page, pageSize) => {
                            state.page = page;
                            loadMembers(pageSize, (page - 1) * pageSize);
                        }}
                    />
                </div>
            }
        >
            <Table
                loading={state.loading}
                bordered
                pagination={false}
                size="small"
                dataSource={state.members}
                rowKey="omUuid"
                columns={columns}
                scroll={{ y: cardBodyHeight - 40 }}
            />
        </SemiCard>
    );
}
